import pandas as pd
from mlxtend.preprocessing import TransactionEncoder
from mlxtend.frequent_patterns import apriori, association_rules

# 读取菜品数据
df = pd.read_excel('D:/sb/zsb/test2/餐厅数据 (1).xlsx')

# 转换菜品数据格式
trsation = df['菜品'].str.split(',').to_list()

# print(trsation)

# 标准化数据。
ts = TransactionEncoder()
te_ary = ts.fit(trsation).transform(trsation)
df_enecoded = pd.DataFrame(te_ary, columns=ts.columns_)
# print(df_enecoded)

# 使用apriori进行关联规则挖掘
frequent_itemsets = apriori(df_enecoded, min_support=0.1, use_colnames=True)
frequent_itemsets.sort_values(by='support', ascending=False, inplace=True)

# # 选择2项集
# print(frequent_itemsets[frequent_itemsets.itemsets.apply(lambda x : len(x) == 2)])
# 生产关联规则
rules = association_rules(frequent_itemsets, metric='confidence', min_threshold=0.1)
# 筛选有效规则
effective = rules[
    (rules['lift'] > 1) & (rules['confidence'] > 0.1)
].sort_values(by=['lift', 'confidence'], ascending=False)
# print(effective[['antecedents', 'consequents', 'support', 'confidence', 'lift']])
# 生成相应的模型
frequent_itemsets.to_pickle("D:/sb/zsb/test2/frequent_itemsets.pkl")
effective.to_pickle('D:/sb/zsb/test2/rule.pkl')